package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.StatusConstant;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.exception.TheCategoryHasSomethingSetmeal;
import com.sky.exception.TheCategoryHasSonemthingDish;
import com.sky.mapper.CategoryMapper;
import com.sky.result.PageResult;
import com.sky.service.CategoryServise;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServisempl implements CategoryServise {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public void addCategory(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO,category);
        //设置默认状态为启用
        category.setStatus(StatusConstant.ENABLE);
//        //设置创建时间和修改时间
//        category.setCreateTime(LocalDateTime.now());
//        category.setUpdateTime(LocalDateTime.now());
//        //设置创建人id和修改人id
//        category.setCreateUser(BaseContext.getCurrentId());
//        category.setUpdateUser(BaseContext.getCurrentId());
        //保存到数据库
        categoryMapper.insert(category);

    }

    //修改分类

    @Override
    public void edit(CategoryDTO categoryDTO) {

        categoryMapper.editCategory(categoryDTO);
    }

    @Override
    public PageResult pageQuery(CategoryPageQueryDTO cpqd) {
        PageHelper.startPage(cpqd.getPage(), cpqd.getPageSize());
        List<Category> rows = categoryMapper.selectByPage(cpqd);
        Page<Category> p = (Page<Category>) rows;
        return new PageResult(p.getTotal(), p.getResult());
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        categoryMapper.updateStatus(status,id);
    }

    @Override
    public void delete(Long id) {
        //判断分类下是否还有菜品再选择删除
        List<Integer> integers = categoryMapper.selectDishByCategoryId(id);
        if(integers.size()>0){
            throw new TheCategoryHasSonemthingDish("当前分类下还有菜品，不能删除");
        }


        //判断当前分类是否关联了套餐 再选择删除
        List<Integer> integers1 = categoryMapper.selectSetmealByCategoryId(id);
        if(integers1.size()>0){
            throw new TheCategoryHasSomethingSetmeal("当前分类下还有套餐，不能删除");
        }


        categoryMapper.deleteCategory(id);
    }

    @Override
    public List<Category> list(Integer type) {
        List<Category> categories = categoryMapper.selectByType(type);
        return categories;
    }


}
